const {
  Types: {
    ObjectId: { isValid }
  }
} = require("mongoose")

const Service = require("../../service/topic")

class Topic {
  constructor() {
    this.instance = null
  }
  static get Instance() {
    return this.instance || (this.instance = new Topic())
  }

  async getTopics(ctx) {
    let { pageNum = 10, page = 1, q = '' } = ctx.query
    pageNum = Math.max(pageNum - 0 || 10, 1)
    page = Math.max(page - 0, 1) - 1
    const skipNum = page * pageNum
    const topics = await Service.getTopics(pageNum, skipNum, q)
    ctx.rest(topics)
  }

  async getTopicById(ctx) {
    const { fields = "" } = ctx.query
    const topicId = ctx.params.id
    if (!topicId || !isValid(topicId))
      return ctx.throw(404, "can not get topicId")
    const topic = await Service.getTopicById(topicId, fields)
    if (!topic) return ctx.throw("can not find topic!")
    ctx.rest(topic)
  }

  async addTopic(ctx) {
    ctx.verifyParams({
      name: { type: "string", required: true },
      introduction: { type: "string", required: true },
      avatar_url: { type: "string", required: false }
    })
    const data = ctx.request.body
    const topic = await Service.addTopic(data)
    ctx.rest(topic)
  }

  async delTopicById(ctx) {
    const topicId = ctx.params.id
    if (!topicId || !isValid(topicId))
      return ctx.throw(404, "can not get topicId")
    const topic = await Service.delTopicById(topicId)
    if (!topic) return ctx.throw(404, "can not find topic!")
    ctx.rest(topic)
  }

  async updateTopic(ctx) {
    ctx.verifyParams({
      name: { type: "string", required: false },
      introduction: { type: "string", required: false },
      avatar_url: { type: "string", required: false }
    })
    const data = ctx.request.body
    const topicId = ctx.params.id
    if (!topicId || !isValid(topicId))
      return ctx.throw(404, "the topic id is invalid!")
    const topic = await Service.updateTopic(topicId, data)
    if (!topic) return ctx.throw(404, "can not find this topic!")
    ctx.rest(topic)
  }
}

const I = Topic.Instance

module.exports = I
